package com.yn.xr.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
/**
 * web工具类 
 */
public class WebUtil {
	private static Logger logger = Logger.getLogger(WebUtil.class);
	/**
	 * 异步方式 ，给 客户端写json数据 
	 * @param response
	 * @param msg
	 */
	public static void writeJsonToClient(HttpServletResponse response,String msg) {
		writeStr(response, msg,"text/json");
	}
	/**
	 * 异步方式给客户端些 文本数据
	 * @param response
	 * @param msg
	 */
	public static void writeStrToClient(HttpServletResponse response,
			String msg) {
		writeStr(response, msg,"text/html");
	}
	
	public static void writeStr(HttpServletResponse response,String msg,String type) {
		response.setContentType(type);
		response.setCharacterEncoding("utf-8");
		try {
			response.getWriter().write(msg);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (IOException e) {
			logger.error("网络异常", e);
		}
	}
	
	/**
	 * 获取验证码
	 * @param request
	 * @return
	 */
	public static String getCode(HttpServletRequest request) {
		return request.getSession().getAttribute("code").toString();
	}
	/**
	 * 获取会话中登入密码错误次数
	 * @return
	 */
	public static short getLoginFailCount(HttpServletRequest request){
		HttpSession session = request.getSession();
		short loginFailCount = session.getAttribute("loginFailCount") == null? (short)0:StringTypeUtil.strToShort(String.valueOf(session.getAttribute("loginFailCount")), (short)0);
		return loginFailCount;
	}
	
	/**
	 * 登陆密码错误次数在会话中累加
	 * @param request
	 */
	public static void loginFailCountForSession(HttpServletRequest request){
		HttpSession session = request.getSession();
		short loginFailCount = session.getAttribute("loginFailCount") == null?(short)0:StringTypeUtil.strToShort(String.valueOf(session.getAttribute("loginFailCount")), (short)0);
		loginFailCount ++;
		session.setAttribute("loginFailCount", loginFailCount);
	}
	
	/**
	 * 登陆成功清空session中的密码错误累积次数
	 * @param request
	 */
	public static void clearFailCountSession(HttpServletRequest request){
		request.getSession().setAttribute("loginFailCount", 0);
	}
	
	public static StringBuffer getBaseEmailHttpHead(HttpServletRequest request) {
		StringBuffer sb = null ;
		try {
			InetAddress addr = InetAddress.getLocalHost();
			sb = new StringBuffer("http://" + addr.getHostAddress()).append(request.getServerPort()==80?"":(":" + request.getServerPort())).append(request.getContextPath());
		} catch (UnknownHostException e) {
			logger.error(e);
		}
		
		return sb;
	}

	
	public static String getPicExt(String name) {
		return name.substring(name.lastIndexOf(".")+ 1, name.length());
	}
	
	/**
	 * 防止SQL注入和XSS攻击
	 * @param s
	 * @return
	 */
	public static  String xssEncode(String s) {
		if (s == null || "".equals(s)) {
			return s;
		}
		StringBuilder sb = new StringBuilder(s.length() + 16);
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			switch (c) {
			case '>':
				sb.append('＞');// 全角大于号
				break;
			case '<':
				sb.append('＜');// 全角小于号
				break;
			case '\'':
				sb.append('‘');// 全角单引号
				break;
			case '\"':
				sb.append('“');// 全角双引号
				break;
			case '&':
				sb.append('＆');// 全角
				break;
			case '\\':
				sb.append('＼');// 全角斜线
				break;
			case '#':
				sb.append('＃');// 全角井号
				break;
			case ';':
				sb.append('；');
				break;
			default:
				sb.append(c);
				break;
			}
		}
		String tempstr =  sb.toString().toLowerCase();
		if(tempstr.indexOf("script")!=-1){
			//sb.toString().replaceAll("script", "");
			tempstr = tempstr.replaceAll("script", "");	//2015.08.11 代码优化。。。。yangjun
		}
		if(tempstr.indexOf("javascript")!=-1){
			//sb.toString().replaceAll("javascript", "");
			tempstr = tempstr.replaceAll("javascript", "");	//2015.08.11 代码优化。。。。yangjun
		}
		if(tempstr.indexOf("vbscript")!=-1){
			//sb.toString().replaceAll("vbscript", "");
			tempstr = tempstr.replaceAll("vbscript", "");	//2015.08.11 代码优化。。。。yangjun
		}
		return tempstr;
	}

	
	/**
	 * 通过HttpServletRequest返回IP地址
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return ip String
	 * @throws Exception
	 * @author HX1501337 李韩刚
	 */
	public static String getIpAddr(HttpServletRequest request) throws Exception {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		logger.info("通过HttpServletRequest返回IP地址,IP=[" + ip + "]");
		return ip;
	}

	/**
	 * 通过IPv4地址获取MAC地址
	 * 
	 * @param ip
	 *            String,127.0.0.1格式
	 * @return mac String
	 * @throws Exception
	 * @author HX1501337 李韩刚
	 */
	public static String getMACAddress(String ip) throws Exception {
		logger.info("通过IP=[" + ip + "]地址获取MAC地址");
		String line = "";
		String macAddress = "";
		try {
			final String loopback_address = "127.0.0.1";
			// 如果为127.0.0.1,则获取本地MAC地址。
			if (loopback_address.equals(ip)) {
				InetAddress inetAddress = InetAddress.getLocalHost();
				// 貌似此方法需要JDK1.6。
				byte[] mac = NetworkInterface.getByInetAddress(inetAddress).getHardwareAddress();
				// 下面代码是把mac地址拼装成String
				StringBuilder sb = new StringBuilder();
				for (int i = 0; i < mac.length; i++) {
					if (i != 0) {
						sb.append("-");
					}
					// mac[i] & 0xFF 是为了把byte转化为正整数
					String s = Integer.toHexString(mac[i] & 0xFF);
					sb.append(s.length() == 1 ? 0 + s : s);
				}
				// 把字符串所有小写字母改为大写成为正规的mac地址并返回
				macAddress = sb.toString().trim().toUpperCase();
				return macAddress;
			}
		} catch (Exception e) {
			logger.error("获取本地IP的MAC地址," + e.getMessage(), e);
		}

		// 获取非本地IP的MAC地址
		try {
			Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
			InputStreamReader isr = new InputStreamReader(p.getInputStream());
			BufferedReader br = new BufferedReader(isr);
			String MAC_ADDRESS_PREFIX_A = "MAC Address = ";
			String MAC_ADDRESS_PREFIX_D = "MAC 地址 = ";
			String MAC_ADDRESS_PREFIX = "MAC";
			while ((line = br.readLine()) != null) {
				if (line != null) {
					int index_a = line.indexOf(MAC_ADDRESS_PREFIX_A);
					int index_d = line.indexOf(MAC_ADDRESS_PREFIX_D);
					int index = line.indexOf(MAC_ADDRESS_PREFIX);
					if (index_a > 0) {
						macAddress = line.substring(index_a + MAC_ADDRESS_PREFIX_A.length()).trim().toUpperCase();
						break;
					} else if (index_d > 0) {
						macAddress = line.substring(index_d + MAC_ADDRESS_PREFIX_D.length()).trim().toUpperCase();
						break;
					} else if (index > 0) {
						macAddress = line.substring(line.indexOf("=") + 2, line.length());
						break;
					}
				}
			}
			br.close();
		} catch (Exception e) {
			logger.error("获取非本地IP的MAC地址," + e.getMessage(), e);
		}
		logger.info("通过IP=[" + ip + "]地址获取MAC地址=[" + macAddress + "]");
		return macAddress;
	}
}
